package org.klaoye.musicplayer;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

import org.klaoye.musicplayer.bean.ReceiverStrings;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Arrays;

public class MusicService extends Service implements ReceiverStrings {
    File[] musicFiles = null;//播放文件列表
    int musicListPosition = 0;
    int curPosition = 0;
    MediaPlayer mp = new MediaPlayer();
    NotificationManager notificationManager;
    BroadcastReceiver receiver;
    IntentFilter intentFilterA, intentFilterN;
    final String[] law = {".mp3", ".wav"};
    final FileFilter filter = file -> {
        if (file.isDirectory()) return false;
        if (file.exists() && !file.isHidden()) {
            String name = file.getName();
            for (String s : law) {
                if (name.endsWith(s)) return true;
            }
        }
        return false;
    };

    public MusicService() {

    }

    @Override
    public void onCreate() {
        super.onCreate();
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mp.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);//防止后台休眠
        mp.setOnCompletionListener(mp -> {//播放完毕监听器
            musicListPosition++;
            if (musicListPosition >= musicFiles.length) musicListPosition = 0;
            mp.stop();
            try {
                curPosition = 0;
                makeBroadcast(musicFiles[musicListPosition].getName());
                mp.setDataSource(musicFiles[musicListPosition].getPath());
                mp.prepare();
                mp.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        intentFilterA = new IntentFilter(BROADCAST_ACTIVITY);
        intentFilterN = new IntentFilter(BROADCAST_NOTIFICATION);
        receiver = createReceiver();
        registerReceiver(receiver, intentFilterA);
        registerReceiver(receiver, intentFilterN);

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        operator(intent.getData());
        //throw new UnsupportedOperationException("Not yet implemented");

        return new Binder();
    }

    @Override
    public boolean onUnbind(Intent intent) {

        return super.onUnbind(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent.getData() != null) {
            operator(intent.getData());
        }
        notificationCreate();
        return super.onStartCommand(intent, flags, startId);
    }

    private void operator(Uri uri) {//操作函数判断文件类型操作
        File file = new File(uri.getPath());
        Log.i("PlayMusic:", file.getAbsolutePath());
        if (file.isFile()) {
            if (!mp.isPlaying()) {
                try {
                    mp.setDataSource(this, uri);
                    mp.prepare();
                    mp.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            musicFiles = file.listFiles(filter);
            System.out.println("OnStart:" + Arrays.toString(musicFiles));
        }
    }

    private void notificationCreate() {//通知构建函数
        Notification.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//判断8.0及以上版本
            builder = new MyNotificationBuilder(this, "12");
            @SuppressLint("WrongConstant")
            NotificationChannel channel = new NotificationChannel("12", "keyboard", NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(channel);
        } else {
            builder = new MyNotificationBuilder(this);
        }
        notificationManager.notify(12, builder.build());
    }

    private BroadcastReceiver createReceiver() {//广播接收器
        return new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int flag = intent.getIntExtra(FLAG_INT, PLAY);
                Log.i("ServiceReceiverFlag", String.valueOf(flag));
                switch (flag) {
                    case PLAY:
                        playList(musicListPosition);
                        break;
                    case PAUSE:
                        mp.pause();
                        curPosition = mp.getCurrentPosition();
                        break;
                    case STOP:
                        mp.stop();
                        mp.reset();
                        //musicListPosition=0;
                        break;
                    case NEXT:
                        musicListPosition++;
                        playList(musicListPosition);
                        break;
                    case LAST:
                        musicListPosition--;
                        playList(musicListPosition);
                        break;
                    default:
                        break;
                }
            }
        };
    }

    private void makeBroadcast(String path) {//设置广播，用于修改通知显示栏文件名
        Intent broadcast = new Intent(BROADCAST_SERVICE).putExtra(FLAG_STRING, path);
        sendBroadcast(broadcast);
    }

    private void playList(final int position) {//循环播放列表函数
        int p = position;
        if (p >= musicFiles.length) p = 0;
        if (p < 0) p = musicFiles.length - 1;
        musicListPosition = p;
        System.err.println(musicListPosition + " " + p);

        makeBroadcast(musicFiles[p].getName());
        playing(musicFiles[p].getPath());

    }

    private void playing(String path) {//音频播放函数
        mp.stop();
        mp.reset();
        try {
            mp.setDataSource(path);
            mp.prepare();
            mp.seekTo(curPosition);
            mp.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        mp.stop();
        mp.release();
        super.onDestroy();
    }
}